<?php

namespace App\Http\Controllers\Api;

use App\Models\Gift;
use App\Models\Hero;
use Dingo\Api\Http\Request;

class GiftController extends BaseController
{
    public function store(Request $request)
    {
        $this->validate($request, [
            'type' => 'required|in:1,2',
            'id' => 'required'
        ]);
        $id = \request('id');
        if (!Hero::find($id)) {
            return $this->failed("ID不存在");
        }
        $user = $this->getUser();
        if (!$user)
            return $this->failed("获取用户信息异常，请重新授权", 401);

        $data = [
            'user_id' => $user->id,
            'appoint_id' => $id,
            'type' => \request('type')
        ];

        if (Gift::create($data)) {
            Gift::flushTags($id);
            return $this->success([], '操作成功');
        }
        return $this->failed('操作失败');
    }

    public function index(Request $request) {
        $this->validate($request, [
            'type' => 'required|in:1, 2',
            'id' => 'required'
        ]);
        $input = $request->input();
        if (!Hero::find($input['id'])) {
            return $this->failed("ID不存在");
        }
        $func = function () {
            return Gift::where('type', \request('type'))
                ->where('appoint_id', \request('id'))
                ->join('users', 'users.id', 'gifts.user_id')
                ->select("users.nickname", "gifts.created_at")
                ->orderBy('gifts.id', 'desc')
                ->paginate(\request('per_page', 20));
        };
        $list = $this->cache($input, Gift::getTagKey($input['id']), $func);
        return $this->paginate($list);
    }

}